// mycomponent/reg-address/reg-address.js
const app = getApp()
const location = require('../../mybehaviors/location/location')
Component({
  behaviors: [location],
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    // 设置地址
    setAddressShow: false,
    areaOptions: [],
    areaShow: false,
    addressValue: {},
    addressText: '',
    verifying: false
  },

  lifetimes: {
    attached() {
      let self = this;
      app.watchGlobalData('currentRoute', self.watchRoute.bind(self))
      this.watchRoute()
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 监听页面切换
     */
    watchRoute: function() {
      const { isExistAddress } = app.globalData
      // 没有注册地址
      if (!isExistAddress) {
        this.isExistAddress()
      }
    },

    /**
     * 验证用户是否存在注册地址
     * @param {Object} address 地址数据
     */
    isExistAddress: function() {
      const { setAddressShow, verifying } = this.data
      if (setAddressShow || verifying) {
        return
      }
      this.setData({ verifying: true })
      const urlStr = app.getNetAddresss('member.address.isExistAddress')
      const _this = this
      app._getNetWork({
        url: urlStr,
        success: function(res) {
          const resData = res.data
          if (resData.result) {
            const isExist = resData.data
            app.globalData.isExistAddress = isExist;
            if (!isExist) {
              // 获取省市县option后显示地址弹窗
              _this._getLocation((res) => {
                _this.getAddress(res)
              },
              (err) => {
                _this.getAddress(err)
              });
            }
          } else {
            app.tips(resData.msg || '验证用户地址失败！')
          }
        },
        compolete: function() {
          _this.setData({ verifying: false })
        }
      })
    },

    /**
     * 获取定位
     */
    getCurrentAddress: function() {
      const _this = this
      wx.getSetting({
        success: function(settingdata) {
          // 已允许获取位置信息
          if (settingdata.authSetting['scope.userLocation']) {
            _this._getLocation((res) => {
              _this.setAddress(res)
            })
          } else {
            // 用户设置拒绝获取用户信息，打开设置
            wx.openSetting({
              success: function(settingdata) {
                if (settingdata.authSetting["scope.userLocation"]) {
                  _this._getLocation((res) => {
                    _this.setAddress(res)
                  })
                } else {
                  app.tips('请允许小程序获取您的位置信息！')
                }
              },
              fail: function(err){
                console.log(err)
              }
            })
          }
        },
        fail: function() {
          app.tips('获取用户设置信息失败！')
        }
      })
    },

    /**
    * 获取省市列表(区域)
    */
    getAddress: function(address = false) {
      const _this = this
      let urlStr = app.getNetAddresss("member.member-address.address");
      app._postNetWork({
        url: urlStr,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            const thirdLevelRegion = resData.data.province.map(item => {
              const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
                const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                  return {
                    text: item2.areaname,
                    value: item2.id + ''
                  }
                })
                return {
                  text: item1.areaname,
                  value: item1.id + '',
                  children: child2
                }
              })
              return {
                text: item.areaname,
                value: item.id + '',
                children: child
              }
            })
            _this.setAddress(address)
            _this.setData({
              areaOptions: thirdLevelRegion,
              setAddressShow: true
            })
          } else {
            app.tips(resData.msg)
          }
        }
      })
    },

    /**
    * 获取省市列表(区域)
    */
    getAddress: function(address = false) {
      const _this = this
      let urlStr = app.getNetAddresss("member.member-address.address");
      app._postNetWork({
        url: urlStr,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            const thirdLevelRegion = resData.data.province.map(item => {
              const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
                const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                  return {
                    text: item2.areaname,
                    value: item2.id + ''
                  }
                })
                return {
                  text: item1.areaname,
                  value: item1.id + '',
                  children: child2
                }
              })
              return {
                text: item.areaname,
                value: item.id + '',
                children: child
              }
            })
            _this.setAddress(address)
            _this.setData({
              areaOptions: thirdLevelRegion,
              setAddressShow: true
            })
          } else {
            app.tips(resData.msg)
          }
        }
      })
    },

    /**
     * 设置地址
     * @param {Object} address 地址数据
     */
    setAddress: function(address = false) {
      if (!address) return
      const { adcode, province, city, district} = address.ad_info
      this.setData({
        addressValue: {
          province_id: adcode.substr(0, 2) + '0000',
          province,
          city_id: adcode.substr(0, 4) + '00',
          city,
          district_id: adcode,
          district
        },
        addressText: [province, city, district].join('/')
      })
    },

    /**
     * 显示
     */
    toggleArea: function(e) {
      const { toggle } = e.currentTarget.dataset
      this.setData({ areaShow: toggle })
    },

    /**
     * 注册区域选中
     * @param {Object} e 
     */
    areaFinish: function(e) {
      const { selectedOptions } = e.detail
      this.setData({
        addressValue: {
          province_id: selectedOptions[0].value,
          province: selectedOptions[0].text,
          city_id: selectedOptions[1].value,
          city: selectedOptions[1].text,
          district_id: selectedOptions[2].value,
          district: selectedOptions[2].text
        },
        addressText: [selectedOptions[0].text, selectedOptions[1].text, selectedOptions[2].text].join('/'),
        areaShow: false
      })
    },

    /**
     * 提交注册地址
     */
    submitAddress: function() {
      const { addressValue } = this.data
      if (!addressValue.district_id) {
        app.tips('请选择注册地址！')
        return
      }
      const _this = this
      const urlStr = app.getNetAddresss('member.address.updateAddress')
      wx.showLoading({ title: '加载中...' })
      app._postNetWork({
        url: urlStr,
        data: addressValue,
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            _this.setData({
              setAddressShow: false
            })
            app.globalData.isExistAddress = 1;
            app.tips('保存成功！')
          } else {
            app.tips(resData.msg || '保存失败！')
          }
        },
        compolete: function() {
          wx.hideLoading()
        }
      })
    },
  }
})